<template>
  <div class="page-edit">
    <header>
      <i style="font-size: 18px; cursor: pointer; margin-right: 8px" class="el-icon-arrow-left" @click="goBack"></i>
      <span>{{ title }}</span>
    </header>
    <section class="edit-body">
      <div class="form-page">
        <p class="title-level2" v-if="routeName=='TrainRecord'">培训信息</p>
        <el-form ref="form" :model="form" :rules="rules" label-width="200px">
          <el-col :span="8">
            <el-form-item label="培训名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入培训名称" :readonly="!isEdit" :disabled="!isEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="讲师" prop="lecturer">
              <el-input v-model="form.lecturer" placeholder="请输入讲师" :readonly="!isEdit" :disabled="!isEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="培训开始时间" prop="startTime">
              <el-date-picker clearable :readonly="!isEdit" :disabled="!isEdit" v-model="form.startTime" type="date"
                value-format="yyyy-MM-dd" placeholder="选择培训开始时间" :picker-options="pickerOptionsStart">
              </el-date-picker>
            </el-form-item>              
          </el-col>
          <el-col :span="8">
            <el-form-item label="培训结束时间" prop="endTime">
              <el-date-picker clearable :readonly="!isEdit" :disabled="!isEdit" v-model="form.endTime" type="date"
                value-format="yyyy-MM-dd" placeholder="选择培训结束时间" :picker-options="pickerOptionsEnd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="培训关联课程" prop="trainCourseIds">
              <el-select v-model="form.trainCourseIds" placeholder="请选择培训关联课程" clearable multiple :readonly="!isEdit" :disabled="!isEdit">
                <el-option
                  v-for="dict in courseLists"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"          
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="routeName=='TrainRecord'">
            <el-form-item label="培训状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择培训状态" clearable :readonly="!isEdit" :disabled="!isEdit">
                <el-option
                  v-for="dict in courseStatusList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"          
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="培训简介" prop="profiles">
              <el-input v-model="form.profiles" type="textarea" placeholder="请输入培训简介"  
                :rows="3"
                show-word-limit
                maxlength="300"
                :readonly="!isEdit"
                :disabled="!isEdit" />
            </el-form-item>
          </el-col>
        </el-form>
      </div>
      <div class="form-page">
        <p class="title-level2">人员信息</p>
        <el-button v-if="isEdit" type="primary" @click="handleUsersAdd" style="margin-bottom:10px;margin-left:60px">添加人员</el-button>
        <SelectUser ref="users" @getData="getSelectedUsers" :selectedUsers="selectedUsers"/>
        <div class="users-sel" style="margin-left:60px">
          <elTables   
            :curHeight="390"
            :columns="columns"
            :table-data="selectedUsers"
          ></elTables>
        </div>
      </div>
    </section>
    <footer v-if="isEdit">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </footer>
  </div>
</template>

<script>
const defaultQueryParams = {
  pageNum: 1,
  pageSize: 10,
};
import { getToken } from "@/utils/auth";
import { addTrain, updateTrain } from "@/api/edu/train";
import { listCourse } from "@/api/edu/course";
import SelectUser  from '../../../components/selectUser.vue'

export default {
  name: "Detail",
  props: ['title','isEdit','form'],
  components:{ SelectUser },
  data() {
    return {
      // 开始时间限制
      pickerOptionsStart: {
        disabledDate: (time) => {
          if (this.form.endTime) {
            return time.getTime() > new Date(this.form.endTime).getTime();
          }
        },
      },
      // 结束时间限制
      pickerOptionsEnd: {
        disabledDate: (time) => {
          if(this.form.startTime){
            return time.getTime() < new Date(this.form.startTime).getTime();
          }
        },
      },
      courseLists:[],
      tableHeight: 0,
      dialogFormVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 是否显示弹出层
      open: false,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API + "/edu/train/importData",
      },
      tableData: [],
      // 查询参数
      queryParams: {
        ...defaultQueryParams,
        name: null,
        status: null,
        factoryId: null,
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        lecturer: [
          { required: true, message: "讲师不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        trainCourseIds: [
          { required: true, message: "培训关联课程不能为空", trigger: "change" }
        ],
        profiles: [
          { required: true, message: "培训简介不能为空", trigger: "blur" }
        ],
      },
      userRules:{
        trainUsers:[{required:true,message:'请选择培训人员',trigger:['change','blur']}]
      },
      selectedUsers:[],
      statusList:{
        1:'未开始',
        2:'未完成',
        3:'已完成',
      },
      courseStatusList:[
        {label:'未开始',value:'2'},
        {label:'进行中',value:'3'},
        {label:'已结束',value:'4'},
      ],
      routeName:this.$route.name,
      userForm:{},
    };
  },
  created() {
    this.getCourseLists();
  },
  mounted() {
  },
  computed: {
    columns() {
      let data=[
        {key:'userName',title:'姓名',show:true},
        {key:'deptName',title:'部门',show:true},
        {key:'rate',title:'完成度',show:false},
        {key:'completeTime',title:'完成时间',show:false},
        {key:'status',title:'状态',show:false,render:(h, params) => {
          return h('el-tag',
          {},
          this.statusList[params.row.status]);
        }},
        {
          title: "操作",
          align: "center",
          fixed: 'right',
          width: 80,
          show:true,
          render: (h, params) => {
            return h("div", [
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["edu:train:remove"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleDelete(params.row)
                    },
                  },
                },
                "删除"
              ),
            ]);
          },
        },
      ];
      if(this.routeName=='TrainRecord'){
        data=data.slice(0,-1);
      }else{
        if(this.isEdit){
          data=data.filter(_ => _.show);
        }else{
          data=data.slice(0,2);
        }
      }
      return data
    }
  },
  watch:{
    form(value) {
      console.log('values',value)
      if (value) {
        this.selectedUsers=value.trainUsers;
      }
    },
  },
  methods: {
    getSelectedUsers(data){
      console.log('trainUsers',data);
      this.form.trainUsers=data.map(_ => {
        return {
          userId:_.userId
        }
      });
      this.selectedUsers=data;
    },
    handleUsersAdd(){
      this.$refs.users.dialogFormVisible=true;
    },
    goBack() {
      this.$emit('back');
    },
    // 查询所有课程列表
    getCourseLists() {
      this.loading = true;
      listCourse({}).then(response => {
        if(response.code==200){
          this.courseLists = response.data;
        }else{
          this.$message.error(response.message)
        }
      });
    },
    // 取消按钮
    cancel() {
      this.$emit('back')
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 提交按钮 */
    submitForm() {
      const staticParams={
        createBy:undefined,
        createTime:undefined,
        updateBy:undefined,
        updateTime:undefined,
        createDept:undefined,
        delFlag:undefined,
        releaseStatus:undefined,
        status:undefined,
        userNum:undefined
      };
      let params={
        ...this.form,
        ...staticParams,
      };
      console.log('this.form',this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(!this.form.trainUsers || this.form.trainUsers.length==0){
            return this.$message.error('请添加培训人员！')
          }
          if (this.form.id != null) {
            updateTrain(params).then(response => {
              this.msgSuccess("修改成功");
              this.$emit('back');
            });
          } else {
            addTrain(params).then(response => {
              this.msgSuccess("新增成功");
              this.$emit('back');
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const name = row.userName;
      this.$confirm('是否确认删除?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        console.log('this.selectedUsers',this.selectedUsers);
        this.selectedUsers=this.selectedUsers.filter(_ => _.userId!= row.userId);
        this.form.trainUsers=this.selectedUsers;
        this.msgSuccess("删除成功");
      })
    },
  }
};
</script>
<style lang="scss" scoped>
.users-sel ::v-deep {
  .el-table{
    overflow: hidden !important;
  }
}
</style>